package com.yuntongxun.ecdemo.ui.contact;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;

import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.dialog.ECProgressDialog;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.core.ContactsCache;
import com.yuntongxun.ecdemo.rest.RetrofitUtil;
import com.yuntongxun.ecdemo.rest.interfaces.UserInterface;
import com.yuntongxun.ecdemo.rest.models.ServerResult;
import com.yuntongxun.ecdemo.rest.models.UserModel;
import com.yuntongxun.ecdemo.ui.ECSuperActivity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class AddContactActivity extends ECSuperActivity {

    final Random _random = new Random();
    ArrayList<UserModel> _users = new ArrayList<UserModel>();
    ListView _listView;
    private int _pageindex = 0;
    private ECProgressDialog _waitingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        (_listView = (ListView) findViewById(R.id.listView)).setAdapter(new UsersAdapter(this, _users));
        addControlsEvents();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ((SearchView) findViewById(R.id.searchView)).onActionViewExpanded();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_contact;
    }

    private void addControlsEvents() {
        // search view
        SearchView searchView = (SearchView) findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                _pageindex = 0;
                showWaitingDialog(R.string.please_wait);
                UserInterface usersInterface = RetrofitUtil.createRestApi(UserInterface.class);
                usersInterface.search(s, _pageindex, new Callback<UserModel[]>() {
                    @Override
                    public void success(final UserModel[] userModels, Response response) {
                        dismissWaitingDialog();
                        if(userModels == null || userModels.length < 1) {
                            ToastUtil.showMessage(R.string.no_result);
                            return;
                        }
                        for(UserModel u : userModels) {
                            if(ContactsCache.getInstance().isMyContact(u.getAccount())) {
                                u.setStatus(2);
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showContacts(userModels);
                            }
                        });
                    }

                    @Override
                    public void failure(final RetrofitError error) {
                        dismissWaitingDialog();
                        ToastUtil.showMessage(
                                String.format("%s,%s", getString(R.string.failed_to_search), error.getMessage()));
                    }
                });
                return true;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });
    }

    private void showContacts(UserModel[] users) {
        _users.clear();
        _users.addAll(Arrays.asList(users));
        ((ArrayAdapter)_listView.getAdapter()).notifyDataSetChanged();
    }

    private void sendFriendRequest(final String friendAccount) {
        UserInterface usersInterface = RetrofitUtil.createRestApi(UserInterface.class);
        usersInterface.requestFriend(CCPAppManager.getUserId(), friendAccount, "", new Callback<ServerResult>() {
            @Override
            public void success(final ServerResult serverResult, Response response) {
                String msg = "";
                if(serverResult.getErrno() == 0) {
                    msg = getString(R.string.success_to_request_friend);
                } else {
                    msg = String.format("%s,%s",
                            getString(R.string.failed_to_request_friend),
                            serverResult.getMsg());
                }
                ToastUtil.showMessage(msg);
                //
                for(UserModel usr : _users) {
                    if(usr.getAccount().equalsIgnoreCase(friendAccount)) {
                        usr.setStatus(1);
                        break;
                    }
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((ArrayAdapter)_listView.getAdapter()).notifyDataSetChanged();
                    }
                });
            }

            @Override
            public void failure(final RetrofitError error) {
                ToastUtil.showMessage(
                        String.format("%s,%s", getString(R.string.failed_to_request_friend), error.getMessage()));
            }
        });
    }

    public class UsersAdapter extends ArrayAdapter<UserModel> {
        public UsersAdapter(Context context, ArrayList<UserModel> users) {
            super(context, 0, users);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.add_contact_list_item, parent, false);
            }
            //
            ImageView ivAvatar = (ImageView) convertView.findViewById(R.id.avatar_iv);
            TextView tvName = (TextView) convertView.findViewById(R.id.name_tv);
            TextView tvDesc = (TextView) convertView.findViewById(R.id.description_tv);
            Button btn = (Button)convertView.findViewById(R.id.add_contact_btn);
            //
            final UserModel user = getItem(position);
            String remark = ContactLogic.CONVER_PHONTO[_random.nextInt(4)];
            ivAvatar.setImageBitmap(ContactLogic.getPhoto(remark));
            tvName.setText(user.getName());
            tvDesc.setText(String.format("%s %s", user.getGenderDesc(), getAgeDesc(user)));
            if(user.getStatus() == 2) {
                btn.setEnabled(false);
                btn.setText(R.string.friend);
                btn.setOnClickListener(null);
            } else if(user.getStatus() == 1) {
                btn.setEnabled(false);
                btn.setText(R.string.wait);
                btn.setOnClickListener(null);
            } else {
                btn.setEnabled(true);
                btn.setText(R.string.add);
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        sendFriendRequest(user.getAccount());
                    }
                });
            }
            //
            return convertView;
        }
    }

    private String getAgeDesc(UserModel user) {
        return user != null && user.getAge() != null && !user.getAge().isEmpty() ? user.getAge() + getResources().getString(R.string.yearsold) : "";
    }

    private void showWaitingDialog(int resId) {
        if(_waitingDialog == null) {
            _waitingDialog = new ECProgressDialog(this, resId);
            _waitingDialog.show();
        }
    }

    private void dismissWaitingDialog() {
        if (_waitingDialog == null || !_waitingDialog.isShowing()) {
            return;
        }
        _waitingDialog.dismiss();
        _waitingDialog = null;
    }
}
